<?php
namespace app\v1\controller;

use support\Request;
use app\model\Util;
use app\model\GoodsModel;
use app\model\GoodsImageModel;
use app\model\GoodsSpecModel;
use app\model\GoodsCatModel;
use app\model\GoodsKuModel;
use app\model\OrderModel;
use app\model\OrderItemModel;
use app\model\CardUserModel;
use Exception;
use support\Db;
use EasyWeChat\Factory;
use app\model\UserModel;
use app\model\CardItemModel;
use app\model\ScoreLogModel;
use app\model\AddressModel;
use app\model\MiniParsedown;
use app\model\PayPingModel;

class GoodsController {
    
    /**
     * 获取严选商品列表
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request)
    {
        try {
            $page = $request->get('page', 1);
            $limit = $request->get('limit', 10);
            $catId = $request->get('cat_id', 0);
            $subCatId = $request->get('sub_cat_id', 0);
            
            // 构建查询条件
            $query = GoodsModel::where('status','=','online');
            
            if ($catId > 0) {
                $query->where('cat_id', $catId);
            }
            
            if ($subCatId > 0) {
                $query->where('sub_cat_id', $subCatId);
            }
            
            // 获取商品列表
            $goods = $query->orderBy('sort_by', 'desc')
                          ->orderBy('id', 'desc')
                          ->offset(($page - 1) * $limit)
                          ->limit($limit)
                          ->get();
            
            $goodsList = [];
            foreach ($goods as $item) {
                $minPrice = $item->minPrice();
                $goodsList[] = [
                    'id' => $item->id,
                    'title' => $item->title,
                    'image' => Util::pathToUrl($item->image),
                    'sort_by' => $item->sort_by,
                    'cat_id' => $item->cat_id,
                    'sub_cat_id' => $item->sub_cat_id,
                    'created_at' => $item->created_at,
                    'current_price' => $minPrice ? ['price' => $minPrice->price] : ['price' => 0],
                    'sellout_count' => $item->sellout_count ?? 0,
                    'star_value' => ($item->star ?? 0) * 20,
                    'pre_sale' => $item->pre_sale
                ];
            }
            
            // 获取总数
            $total = $query->count();
            
            return json([
                'data' => [
                    'list' => $goodsList,
                    'total' => $total,
                    'page' => $page,
                    'limit' => $limit
                ],
                'msg' => '获取严选商品列表成功',
                'code' => 1
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 搜索商品
     * @param Request $request
     * @return mixed
     */
    public function search(Request $request)
    {
        try {
            $keyword = $request->get('keyword', '');
            $page = $request->get('page', 1);
            $limit = $request->get('limit', 10);
            
            if (empty($keyword)) {
                throw new Exception('搜索关键词不能为空');
            }
            
            // 构建搜索查询条件
            $query = GoodsModel::where('status', '=', 'online')
                ->where(function($query) use ($keyword) {
                    $query->where('title', 'like', '%' . $keyword . '%')
                          ->orWhere('name', 'like', '%' . $keyword . '%');
                });
            
            // 获取商品列表
            $goods = $query->orderBy('sort_by', 'desc')
                          ->orderBy('id', 'desc')
                          ->offset(($page - 1) * $limit)
                          ->limit($limit)
                          ->get();
            
            $goodsList = [];
            foreach ($goods as $item) {
                $minPrice = $item->minPrice();
                $goodsList[] = [
                    'id' => $item->id,
                    'title' => $item->title,
                    'name' => $item->name,
                    'image' => Util::pathToUrl($item->image),
                    'sort_by' => $item->sort_by,
                    'cat_id' => $item->cat_id,
                    'sub_cat_id' => $item->sub_cat_id,
                    'created_at' => $item->created_at,
                    'current_price' => $minPrice ? ['price' => $minPrice->price] : ['price' => 0],
                    'sellout_count' => $item->sellout_count ?? 0,
                    'star_value' => ($item->star ?? 0) * 20
                ];
            }
            
            // 获取总数
            $total = $query->count();
            
            return json([
                'data' => $goodsList,
                'total' => $total,
                'msg' => '搜索商品成功',
                'code' => 1
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 获取商品分类树
     * @param Request $request
     * @return mixed
     */
    public function categories(Request $request)
    {
        try {
            // 获取所有启用的商品分类
            $categories = GoodsCatModel::where('status', 1)
                    ->where('fid','=',0)
                                     ->orderBy('sort', 'asc')
                                     ->orderBy('id', 'asc')
                                     ->get();
            
            $categoryTree = [];
            $catMap = [];
            
            // 构建分类树结构
            foreach ($categories as $category) {
                $catMap[] = [
                    'id' => $category->id,
                    'text' => $category->name,
                ];
            }
            
            
            return json([
                'data' => $catMap,
                'msg' => '获取商品分类成功',
                'code' => 1
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 获取指定分类的二级分类列表
     * @param Request $request
     * @return mixed
     */
    public function subCategories(Request $request)
    {
        try {
            $catId = $request->get('cat_id', 0);
            
            if (empty($catId)) {
                throw new Exception('分类ID不能为空');
            }
            
            // 获取指定分类的二级分类
            $subCategories = GoodsCatModel::where('status', 1)
                    ->where('fid', $catId)
                    ->orderBy('sort', 'asc')
                    ->orderBy('id', 'asc')
                    ->get();
            
            $subCatList = [];
            foreach ($subCategories as $subCat) {
                $subCatList[] = [
                    'id' => $subCat->id,
                    'text' => $subCat->name,
                ];
            }
            
            return json([
                'data' => $subCatList,
                'msg' => '获取二级分类成功',
                'code' => 1
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 获取商品详情
     * @param Request $request
     * @return mixed
     */
    public function one(Request $request)
    {
        try {
            $id = $request->get('id', 0);
            
            if (empty($id)) {
                throw new Exception('商品ID不能为空');
            }
            
            $model = GoodsModel::find($id);
            
            if (!$model) {
                throw new Exception('商品不存在');
            }

            $goodsData = [
                'id' => $model->id,
                'title' => $model->title,
                'name' => $model->name,
                'image_url' => Util::pathToUrl($model->image),
                'sort_by' => $model->sort_by,
                'cat_id' => $model->cat_id,
                'sub_cat_id' => $model->sub_cat_id,
                'sellout_count' => $model->sellout_count,
                'star' => $model->star,
                'is_second' => false,
                'content' => $model->content,
                'pre_sale' => $model->pre_sale,
                'pre_sale_start_at' => $model->pre_sale == 1 ? date('Y-m-d', $model->pre_sale_start_at) : false,
                'pre_sale_end_at' => $model->pre_sale == 1 ? date('Y-m-d', $model->pre_sale_end_at) : false
            ];

            $goodsData['content'] = empty($goodsData['content']) ? '' : MiniParsedown::instance()->text($goodsData['content']);
            $goodsData['have_content'] = !empty($goodsData['content']);

            // 秒杀商品
            if($model->second_day == date('Y-m-d')){
                $goodsData['is_second'] = true;
                $goodsData['second_timer'] = (strtotime($model->second_day) + 86400 - time())*1000;

            }

            if($model->pre_sale == 1){
                // 支持人数（已支付下单人数，去重用户ID）
                $goodsData['pre_sale_person_count'] = OrderItemModel::where('goods_id', $id)
                    ->distinct('user_id')
                    ->count('user_id');
                $goodsData['pre_sale_order_count'] = OrderItemModel::where('goods_id', $id)
                ->sum('quantity');
                // 结束时间
                $goodsData['pre_sale_short_end_at'] = date('m.d H:i', ($model->pre_sale_end_at + 86400 - 1));
            }

            $images = GoodsImageModel::where('goods_id', '=', $id)->get();
            $imagesData = [
                [
                    'image_url' => Util::pathToUrl($model->image),
                ]
            ];
            foreach ($images as $image) {
                $imagesData[] = [
                    'image_url' => Util::pathToUrl($image->path),
                ];
            }

            $specs = GoodsSpecModel::where('goods_id', '=', $id)->get();
            $specsData = [];
            foreach ($specs as $spec) {
                $specsData[] = [
                    'name' => $spec->spec_name,
                    'vs' => explode('@', $spec->spec_value),
                ];
            }

            $minPrice = GoodsKuModel::where('goods_id','=',$id)
                ->where('v','>',0)->orderBy('price','asc')->first();
            if(!empty($minPrice)){
                $minPrice['price'] = round($minPrice['price'],2);
            }

            $saleSpecsFormId = GoodsKuModel::where('goods_id','=',$id)->get();
            $saleSpecsFormIdData = [];
            foreach ($saleSpecsFormId as $spec) {
                $saleSpecsFormIdData[] = [
                    'id' => $spec->id,
                    'price' => $spec->price,
                    'pre_success_order_quantity_total' => $spec->pre_success_order_quantity_total,
                    'vs' => str_replace('@', '/', $spec->specs),
                    'pre_success_progress'=>rand(2,3),
                    'v' => $spec->v
                ];
            }

            return json([
                'data' => [
                    'goods' => $goodsData,
                    'images' => $imagesData,
                    'specs' => $specsData,
                    'currentPrice'=>$minPrice,
                    'saleSpecsFormId' => $saleSpecsFormIdData
                ],
                'msg' => '获取商品详情成功',
                'code' => 1
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    public function buy(Request $request) {
        try {
            $user = $request->userLogin;
            $input = $request->post('data');

            if (empty($input['goods_id'])) {
                throw new Exception('商品ID不能为空');
            }

            if (empty($input['quantity']) || $input['quantity'] <= 0) {
                throw new Exception('商品数量不能为空');
            }

            if (empty($input['address_id'])) {
                throw new Exception('收货地址不能为空');
            }

            $goods = GoodsModel::find($input['goods_id']);
            if (!$goods) {
                throw new Exception('商品不存在');
            }

            $address = AddressModel::find($input['address_id']);
            if (empty($address)) {
                throw new Exception('收货地址不存在');
            }

            $expressType = $input['express_type'];
            if($expressType == 'pickUpPoint'){
                if(empty($input['pick_up_point_id'])){
                    throw new Exception('自提点不能为空');
                }
            }

            $ku_id = $input['sku_id'];

            $ku = GoodsKuModel::where('goods_id','=',$input['goods_id'])
                ->where('id','=',$ku_id)
                ->first();
            
            if (!$ku) {
                throw new Exception('该规格组合不存在');
            }

            if ($ku->v < $input['quantity']) {
                throw new Exception('库存不足');
            }

            $o = new OrderModel();
            $o->user_id = $user->id;
            $amount = $ku->price * $input['quantity'];

            $vipDiscount = $goods->vip_discount;
            if($vipDiscount > 0 && $user->isVip() && $vipDiscount < 100){
                // 有折扣
                $pay_amount = round(($amount * ($vipDiscount / 100)),2);
                $discount_amount = round(($amount - $pay_amount),2);
            }else{
                // 无折扣
                $pay_amount = $amount;
                $discount_amount = 0;
            }
            
            $o->total_amount = $amount;
            $o->pay_amount = $pay_amount;
            $o->discount_amount = $discount_amount;
            $o->status = 0;
            $o->pay_status = 0;
            $o->pay_time = 0;
            $o->created_at = time();
            $o->updated_at = time();
            $o->sender_phone = $user->phone;

            // 地址
            $o->express_type = $expressType;
            if($expressType == 'pickUpPoint'){
                $o->pick_up_point_id = $input['pick_up_point_id'];
            }
            $o->address_id = $address->id;
            $o->delivery_status = 0;
            $o->receiver_name = $address->name;
            $o->receiver_phone = $address->phone;
            $o->receiver_province = $address->province;
            $o->receiver_city = $address->city;
            $o->receiver_district = $address->district;
            $o->receiver_address = $address->detail;

            $o->save();

            $oi = new OrderItemModel();
            $oi->order_id = $o->id;
            $oi->goods_id = $input['goods_id'];
            $oi->goods_ku_id = $ku->id;
            $oi->goods_title = $goods->name;
            $oi->goods_image = $goods->image;
            // $oi->sku_specs = json_encode($input['specs'],256);
            //$oi->sku_spec_names = json_encode($specsData,256);
            $oi->unit_price = $ku->price;
            $oi->quantity = $input['quantity'];
            $oi->total_price = $amount;
            $oi->discount_amount = $discount_amount;
            $oi->final_price = $pay_amount;
            $oi->created_at = time();
            $oi->updated_at = time();
            $oi->user_id = $user->id;
            $oi->save();

            return json([
                'code' => 1,
                'msg' => '下单成功，请支付',
                'data' => [
                    'order_id' => $o->id,
                    'total_amount' => $amount,
                    // 'specs' => $sepcStrArr
                ]
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    private function permute($items) {
        if (count($items) <= 1) {
            return [$items];
        }
        $result = [];
        foreach ($items as $key => $item) {
            $rest = $items;
            unset($rest[$key]);
            foreach ($this->permute(array_values($rest)) as $perm) {
                array_unshift($perm, $item);
                $result[] = $perm;
            }
        }
        return $result;
    }

    /**
     * 根据规格组合获取SKU信息（价格和库存）
     * @param Request $request
     * @return mixed
     */
    public function getSkuBySpecs(Request $request)
    {
        try {
            $goods_id = $request->get('goods_id');
            $specs = $request->get('specs');

            if (empty($goods_id) || empty($specs)) {
                return json([
                    'data' => null,
                    'msg' => '参数错误',
                    'code' => 0
                ]);
            }

            // 获取商品信息
            $goods = GoodsModel::find($goods_id);
            if (!$goods) {
                return json([
                    'data' => null,
                    'msg' => '商品不存在',
                    'code' => 0
                ]);
            }

            // 使用重构后的findBySpecsFlexible方法（内部使用whereIn查询优化性能）
            $sku = GoodsKuModel::findBySpecsFlexible($goods_id, $specs);
            
            if (!$sku) {
                return json([
                    'data' => null,
                    'msg' => '该规格组合不存在',
                    'code' => 0
                ]);
            }

            return json([
                'data' => [
                    'id' => $sku->id,
                    'goods_id' => $sku->goods_id,
                    'specs' => $sku->specs,
                    'price' => (float)$sku->price,
                    'stock' => (int)$sku->v,
                    'created_at' => $sku->created_at,
                    'updated_at' => $sku->updated_at
                ],
                'msg' => '获取成功',
                'code' => 1
            ]);

        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 获取商品的所有SKU列表
     * @param Request $request
     * @return mixed
     */
    public function getSkuList(Request $request)
    {
        try {
            $goods_id = $request->get('goods_id');

            if (empty($goods_id)) {
                return json([
                    'data' => null,
                    'msg' => '参数错误',
                    'code' => 0
                ]);
            }

            // 获取商品信息
            $goods = GoodsModel::find($goods_id);
            if (!$goods) {
                return json([
                    'data' => null,
                    'msg' => '商品不存在',
                    'code' => 0
                ]);
            }

            // 获取所有SKU
            $skuList = GoodsKuModel::getByGoodsId($goods_id);
            
            $data = [];
            foreach ($skuList as $sku) {
                $data[] = [
                    'id' => $sku->id,
                    'goods_id' => $sku->goods_id,
                    'specs' => $sku->specs,
                    'sku_code' => GoodsKuModel::generateSkuCode($sku->goods_id, $sku->specs),
                    'price' => (float)$sku->price,
                    'stock' => (int)$sku->v,
                    'created_at' => $sku->created_at,
                    'updated_at' => $sku->updated_at
                ];
            }

            return json([
                'data' => $data,
                'msg' => '获取成功',
                'code' => 1
            ]);

        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 根据SKU编码获取SKU信息
     * @param Request $request
     * @return mixed
     */
    public function getSkuByCode(Request $request)
    {
        try {
            $sku_code = $request->get('sku_code');

            if (empty($sku_code)) {
                throw new Exception('SKU编码不能为空');
            }

            // 根据SKU编码查找SKU
            $sku = GoodsKuModel::findBySkuCode($sku_code);
            
            if (!$sku) {
                throw new Exception('SKU不存在');
            }

            return json([
                'data' => [
                    'id' => $sku->id,
                    'goods_id' => $sku->id,
                    'specs' => $sku->specs,
                    'sku_code' => GoodsKuModel::generateSkuCode($sku->goods_id, $sku->specs),
                    'price' => (float)$sku->price,
                    'stock' => (int)$sku->v,
                    'created_at' => $sku->created_at,
                    'updated_at' => $sku->updated_at
                ],
                'msg' => '获取成功',
                'code' => 1
            ]);

        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 获取严选订单支付信息（云豆余额、福利卡等）
     * @param Request $request
     * @return mixed
     */
    public function getPayInfo(Request $request)
    {
        try {
            $user = $request->userLogin;
            $orderId = $request->get('order_id');

            if (empty($orderId)) {
                throw new Exception('订单ID不能为空');
            }

            // 获取订单信息
            $order = OrderModel::where('id', $orderId)
                ->where('user_id', $user->id)
                ->first();

            if (!$order) {
                throw new Exception('订单不存在');
            }

            // 获取用户云豆余额
            $userScore = $user->score ?? 0;

            // 获取用户福利卡列表（这里需要根据实际的福利卡模型来实现）
            // 暂时返回空数组，实际项目中需要实现福利卡查询逻辑
            $userCards = [];

            // 获取支付金额信息
            $payInfo = [
                'order_id' => $order->id,
                'total_amount' => $order->total_amount,
                'pay_amount' => $order->pay_amount,
                'user_score' => $userScore,
                'user_cards' => $userCards,
                'phone' => $user->phone ?? ''
            ];

            return json([
                'data' => $payInfo,
                'msg' => '获取支付信息成功',
                'code' => 1
            ]);

        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 创建严选订单支付记录
     * @param Request $request
     * @return mixed
     */
    public function createPay(Request $request)
    {
        try {
            $user = $request->userLogin;
            $input = $request->post('data');

            if (empty($input['order_id'])) {
                throw new Exception('订单ID不能为空');
            }

            // 获取订单信息
            $order = OrderModel::where('id', $input['order_id'])
                ->where('user_id', $user->id)
                ->first();

            if (!$order) {
                throw new Exception('订单不存在');
            }

            if ($order->pay_status == 1) {
                throw new Exception('订单已支付');
            }

            $payAmount = $order->pay_amount;
            $useScore = $input['use_score'] ?? 0;
            $useCardScore = $input['use_card_score'] ?? 0;
            $selectedCards = $input['selected_cards'] ?? [];

            $totalCardScore = 0;
            $validatedCards = [];
            // 验证福利卡信息
            if ($useCardScore > 0 && !empty($selectedCards)) {
                foreach ($selectedCards as $cardData) {
                    $cardId = $cardData['card_id'] ?? 0;// card_user.id
                    $cardUseScore = $cardData['use_score'] ?? 0;
                    
                    if ($cardId <= 0 || $cardUseScore <= 0) {
                        throw new Exception('福利卡信息不完整');
                    }
                    
                    // 查询用户卡片信息
                    $cardUser = CardUserModel::where('id', $cardId)
                        ->where('user_id', $user->id)
                        ->where('score', '>=', $cardUseScore)
                        ->where('expired_at', '>', time())
                        ->first();
                    
                    if (!$cardUser) {
                        throw new Exception('福利卡不存在、余额不足或已过期');
                    }
                    
                    $totalCardScore += $cardUseScore;
                    $validatedCards[] = [
                        'card_id' => $cardId,
                        'card_name' => $cardData['card_name'] ?? '',
                        'card_score' => $cardData['card_score'] ?? 0,
                        'use_score' => $cardUseScore,
                        'card_user_id' => $cardUser->id
                    ];
                }
                
                // 验证总使用量
                if (abs($totalCardScore - $useCardScore) > 0.01) {
                    throw new Exception('福利卡云豆使用量计算错误');
                }
            }

            // 验证云豆余额
            if ($useScore > 0) {
                if ($user->score < $useScore) {
                    throw new Exception('云豆余额不足');
                }
            }

            // 计算实际支付金额
            $actualPayAmount = $payAmount - $useScore - $useCardScore;
            if ($actualPayAmount < 0) {
                $actualPayAmount = 0;
            }

            // 开始事务处理
            Db::beginTransaction();

            $baseTradeNo = date('ymd').'-'.str_pad($order->id, 8, '0', STR_PAD_LEFT);
            $order->order_no = $baseTradeNo.'-'.substr(md5($baseTradeNo), 0, 2);
            $order->money = $actualPayAmount;
            $order->score = $useScore;
            $order->card_score = $useCardScore;
            $order->card_score_data = json_encode($validatedCards, JSON_UNESCAPED_UNICODE);
            
            try {
                $config = null;
                if($actualPayAmount > 0){
                    $config = config('wechat.mini_app');
                    $payment = Factory::payment($config);
                    $jssdk = $payment->jssdk;
        
                    $params = [
                        'body' => "严选商品购买",
                        'out_trade_no' => $order->order_no,
                        'total_fee' => $actualPayAmount * 100,
                        'notify_url' => config('site.site_url')."/v1/goods/notify",
                        'trade_type' => 'JSAPI',
                        'openid' => $user->open_id,
                    ];

                    $result = $payment->order->unify($params);
                    if($result['return_code'] != 'SUCCESS'){
                        throw new Exception($result['return_msg']);
                    }

                    if($result['result_code'] != 'SUCCESS'){
                        throw new Exception($result['err_code_des']);
                    }

                    $config = $jssdk->bridgeConfig($result['prepay_id'], false);

                    $order->updated_at = time();
                    $order->save();
                }else{
                    // 扣除云豆余额
                    if ($useScore > 0) {
                        $user->score = round($user->score - $useScore, 2);
                        $user->save();

                        ScoreLogModel::add($order->user_id,$useScore,'credit',ScoreLogModel::OUT,'buy',['item_id'=>$order->id,'comment'=>'严选购物']);
                    }

                    // 扣除福利卡云豆余额
                    if (!empty($validatedCards)) {
                        foreach ($validatedCards as $cardData) {
                            $cardUser = CardUserModel::find($cardData['card_user_id']);
                            if ($cardUser) {
                                $cardUser->score = round($cardUser->score - $cardData['use_score'], 2);
                                $cardUser->use_score = round($cardUser->use_score + $cardData['use_score'], 2);
                                $cardUser->save();

                                ScoreLogModel::add($order->user_id,$cardData['use_score'],'card',ScoreLogModel::OUT,'buy',['item_id'=>$order->id,'comment'=>'严选购物','card_user_id'=>$cardUser->id]);
                                
                                $cardItem = CardItemModel::find($cardUser->card_item_id);
                                if ($cardItem) {
                                    $cardItem->use_score = round($cardItem->use_score + $cardData['use_score'], 2);
                                    $cardItem->save();
                                }
                            }
                        }
                    }

                    // 完全用云豆和福利卡支付

                    $order->status = 1;
                    $order->pay_status = 1;
                    $order->pay_time = time();
                    $order->updated_at = time();
                    $order->save();
                }

                Db::commit();

                $payResult = [
                    'pay_status' => $actualPayAmount <= 0 ? 1 : 0,
                    'remain_money' => $actualPayAmount,
                    'use_score' => $useScore,
                    'use_card_score' => $useCardScore,
                    'wx_pay_config' => $config ?? null // 如果需要微信支付，这里返回支付配置
                ];

                return json([
                    'data' => $payResult,
                    'msg' => '创建支付记录成功',
                    'code' => 1
                ]);

            } catch (Exception $e) {
                Db::rollback();
                throw $e;
            }

        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    public function notify(Request $request){
        try {
            $config = config('wechat.mini_app');
            $payment = Factory::payment($config);
            
            $response = $payment->handlePaidNotify(function ($message, $fail) {
                // 查询支付记录
                $outTradeNo = $message['out_trade_no'];
                $orderId = explode('-', $outTradeNo)[1];
                $orderId = (int)ltrim($orderId, '0');
                
                $order = OrderModel::find($orderId);
                if (!$order) {
                    return $fail('订单不存在');
                }

                // 检查支付状态
                if ($order->pay_status == 1) {
                    return true; // 已经处理过
                }

                // 验证支付金额
                $expectedAmount = (int)($order->pay_amount * 100);
                if ($message['total_fee'] != $expectedAmount) {
                    return $fail('支付金额不匹配');
                }

                // 更新支付记录
                $order->status = 1;
                $order->pay_status = 1;
                $order->pay_time = time();
                $order->transaction_id = $message['transaction_id'];
                $order->save();

                // 扣除用户云豆余额
                if ($order->score > 0) {
                    $user = UserModel::find($order->user_id);
                    if ($user) {
                        $user->score = round($user->score - $order->score, 2);
                        $user->save();
                        ScoreLogModel::add($order->user_id,$order->score,'credit',ScoreLogModel::OUT,'buy',['item_id'=>$order->id,'comment'=>'严选购物']);
                    }
                }

                // 扣除福利卡云豆余额
                if ($order->card_score > 0 && !empty($order->card_score_data)) {
                    $selectedCards = json_decode($order->card_score_data, true);
                    foreach ($selectedCards as $cardData) {
                        $cardId = $cardData['card_id'] ?? 0;
                        $cardUser = CardUserModel::find($cardId);
                        
                        if ($cardUser) {
                            $cardUseScore = min($cardUser->score, (float)($cardData['use_score'] ?? 0));
                            $cardUser->score = round($cardUser->score - $cardUseScore, 2);
                            $cardUser->save();

                            ScoreLogModel::add($order->user_id,$cardUseScore,'card',ScoreLogModel::OUT,'buy',['item_id'=>$order->id,'comment'=>'严选购物','card_user_id'=>$cardUser->id]);

                            $cardItem = CardItemModel::find($cardUser->card_item_id);
                            if ($cardItem) {
                                $cardItem->use_score = round($cardItem->use_score + $cardUseScore, 2);
                                $cardItem->save();
                            }
                        }
                    }
                }

                return true;
            });

            return $response;
        } catch (\Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 查询严选订单支付状态
     * @param Request $request
     * @return mixed
     */
    public function queryPayStatus(Request $request)
    {
        try {
            $user = $request->userLogin;
            $payRecordId = $request->get('pay_record_id');

            if (empty($payRecordId)) {
                throw new Exception('支付记录ID不能为空');
            }

            // 查询支付状态（这里需要根据实际的支付记录模型来实现）
            // 暂时返回未支付状态，实际项目中需要实现支付状态查询逻辑
            $payStatus = 0; // 0=未支付，1=已支付

            return json([
                'data' => [
                    'pay_status' => $payStatus
                ],
                'msg' => '查询支付状态成功',
                'code' => 1
            ]);

        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    public function recommends(Request $request){
        $today = date('Y-m-d');
        $data = GoodsModel::where('recommend_day','=',$today)->limit(2)->get();
        foreach($data as $item){
            $item['image_url'] = Util::pathToUrl($item->image);
            $item['min_price'] = $item->minPrice();

            $item['pre_sale'] = $item->pre_sale;
        }

        return json([
            'code' => 1,
            'data' => $data,
        ]);
    }

    public function pings(Request $request){
        $id = $request->get('id');
        $page = max(1, intval($request->get('page', 1)));
        $limit = max(1, intval($request->get('limit', 10)));
        $offset = ($page - 1) * $limit;

        $query = PayPingModel::where('goods_id', '=', $id)
            ->where('type', '=', 'store-order');

        $total = $query->count();

        $data = $query->orderBy('id', 'desc')
            ->offset($offset)
            ->limit($limit)
            ->get();

        foreach($data as &$item){
            $item['images'] = $item->doImages();
            $item['user'] = UserModel::userCache($item->user_id);
            $item['created_at'] = human_time(strtotime($item->created_at));
        }

        $hasMore = ($offset + $limit) < $total;

        return json([
            'code' => 1,
            'data' => [
                'list' => $data,
                'total' => $total,
                'page' => $page,
                'limit' => $limit,
                'has_more' => $hasMore
            ],
        ]);
    }
} 